package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 认证和授权
 * Author chongge
 * Time 2019/10/31 9:43
 * ClassName com.itheima
 */
@Component
public class MyUserDetailsServiceImpl implements UserDetailsService {

    @Reference
    private UserService userService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.根据用户名查询用户对象(操作数据库)
        User user = userService.findUserByUsername(username);
        //2.用户对象为空 return null
        if (user == null){
            return null;
        }
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();

        //3.授权 用户对象不为空 根据用户Id查询角色关键字和权限表关键字 授予当前登录的用户
        Set<Role> roles = user.getRoles();//角色集合
        if (roles != null){
            for (Role role : roles) {
                grantedAuthorityList.add(new SimpleGrantedAuthority(role.getKeyword()));//授予角色权限 (角色表keyword)
                Set<Permission> permissions = role.getPermissions();
                if (permissions != null && permissions.size() > 0){
                    for (Permission permission : permissions) {
                        //授予权限数据(权限表keyword)
                        grantedAuthorityList.add(new SimpleGrantedAuthority(permission.getKeyword()));
                    }
                }
            }
        }
        //4.String username, String password,Collection<? extends GrantedAuthority> authorities
        return new org.springframework.security.core.userdetails.User(username,user.getPassword(),grantedAuthorityList);
    }
}
